package com.qf.service.impl;

import com.qf.api.CacheFeign;
import com.qf.constant.CacheConstants;
import com.qf.constant.RabbitMQConstants;
import com.qf.constant.ReportStateConstants;
import com.qf.constant.StrategyConstants;
import com.qf.model.StandardReport;
import com.qf.model.StandardSubmit;
import com.qf.service.StrategyService;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 扣费策略
 *
 * @Author ztf
 * @Date 19:45 2021/11/24
 **/
@Service(value = "fee")
@Slf4j
public class FeeServiceImpl implements StrategyService {
    @Autowired
    private CacheFeign cacheFeign;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PushMsgUtil pushMsgUtil;

    /**
     * 策略方法
     *
     * @param standardSubmit
     * @return
     */
    @Override
    public boolean execute(StandardSubmit standardSubmit) {
        log.info("【策略模块-扣费策略】 开始执行", standardSubmit);
        //1. 获取当前客户的余额
        Map<String,String> client = cacheFeign.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID());
        Long balance = Long.parseLong(client.get("fee"));
        //2. 获取当前短信费用
        Long fee = standardSubmit.getFee();
        //3. 判断余额是否够用
        if (balance>fee){
            //4. 扣减费用计算 = 用户余额 - 当前短信费用
            cacheFeign.hincr(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID(),"fee",-fee);
            log.info("【策略模块-扣费策略】 扣费策略执行成功 standardSubmit={}",standardSubmit);
            return true;
        }else {
            log.info("【策略模块-扣费策略】 当前用户余额不足，请及时充值 standardSubmit={}",standardSubmit);
            //5. 如果扣费失败，发送report返回的消息对象到mq队列中，用于通知用户项目，短信发送失败原因
            //将短信发送失败的数据发送到消息回执队列中，最终推送给用户项目
            pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
            //将短信发送失败的数据发送到日志中
            pushMsgUtil.sendLog(standardSubmit,  StrategyConstants.STRATEGY_ERROR_FEE);

            return false;
        }
    }
}
